{% extends "../page.html" %}

{% block head %}
<style type="text/css">
    .panel2 {
        padding-left: 15px;
    }
    .panel1 > .layui-form-item:not(:last-child),
    .panel2 > .layui-form-item:not(:last-child) {
        border-bottom: 1px dashed #e6e6e6;
    }
    .panel2 > .layui-form-item:first-child {
        padding-bottom: 15px;
    }
    @media screen and (max-width: 450px) {
        .panel2 {
            padding: 0;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="layui-row" lay-filter="ArticleForm">
    <div class="layui-col-md9 layui-col-xs12 panel1">
        <div id="id" style="display: none"></div>
        <div class="layui-form-item" id="title"></div>
        <div class="layui-form-item" id="content"></div>
    </div>
    <div class="layui-col-md3 layui-col-xs12 panel2">
        <div class="layui-form-item">
            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="btn_pending">保存为草稿</button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="btn_preview">预览</button>
            <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="btn_publish">发布</button>
        </div>
        <div class="layui-form-item" id="keywords"></div>
        <div class="layui-form-item" id="category_id"></div>
        <div class="layui-form-item" id="cover"></div>
    </div>
</div>
{% endblock %}

{% block script %}
<script type="text/javascript">
    layui.use(["jquery", "yunj", "validate"], function () {
        let win = window;
        let doc = document;
        let $ = layui.jquery;
        let validate = layui.validate;

        class ArticleForm {

            constructor(args) {
                this.args = args;
                this.formId = args.formId;

                this.fieldObjs = {};
                this.init();
                // this.init().catch(e => {
                //     yunj.msg(e);
                // });
            }

            async init() {
                let that = this;
                await that.render();
                that.setEventBind();
            }

            async render() {
                let that = this;
                let fields = that.args.fields;
                for(let i=0;i<fields.length;i++) {
                    let field = fields[i];
                    await new Promise(resolve => {
                        let type = field.type;
                        let options = {
                            formId: that.formId,
                            args: field,
                        };
                        yunj.formField(type, options).then(fieldObj => {
                            return fieldObj.render(`#${field.id}`);
                        }).then(fieldObj => {
                            that.fieldObjs[field.id] = fieldObj;
                            if (fieldObj.id == (that.formId+"_content")) {
                                that.setContentHeight();
                            }
                            resolve(`${field.id} done`);
                        }).catch(err => console.log(err));
                    });
                }
            }

            // 设置内容编辑高度
            setContentHeight() {
                let that = this;
                // 计算元素高度（父元素顶部到页面底部距离-60px）
                let height = $(doc).height() - $("#content").offset().top - 60;
                that.fieldObjs.content.setHeight(height);
            }

            submit(status, callback = null) {
                let that = this;
                let data = yunj.formData(that.formId, validate);
                data.status = status;

                yunj.request(yunj.url(true), data, "post").then(res => {
                    let rawTable = yunj.rawTable('ArticleList');
                    if (rawTable) rawTable.render();
                    let data = res.data;
                    let rawPageWin = yunj.rawPageWin();
                    if (rawPageWin && yunj.isObj(data) && data.hasOwnProperty("redirect")) {
                        yunj.closeCurr();
                        rawPageWin.yunj.openPopup(data.redirect, "文章编辑", true);
                    }
                    callback && callback(res);
                }).catch(e => {
                    yunj.error(e);
                });
            }

            setEventBind() {
                let that = this;

                $(win).resize(function() {
                    // 当窗口大小变化时执行的代码
                    that.setContentHeight();
                });

                $(doc).on("click", "#btn_pending", function (e) {
                    that.submit(11, function (res) {
                        yunj.msg("草稿保存成功");
                    });
                });

                $(doc).on("click", "#btn_preview", function (e) {
                    that.submit(11);
                });

                $(doc).on("click", "#btn_publish", function (e) {
                    that.submit(22, function (res) {
                        yunj.msg("成功发布");
                    });
                });

                // 监听键盘ctrl+s快捷键保存
                doc.addEventListener('keydown', function (e) {
                    if ((e.key === 's' || e.key === 'S') && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
                        e.preventDefault(); // 阻止默认行为
                        that.submit(22, function (res) {
                            yunj.msg("成功发布");
                        });
                    }
                });

            }

        }

        $(doc).ready(function () {
            new ArticleForm({
                formId: "{{ data.formId }}",
                fields: {{ data.fields|tojson|safe }},
            });
        });

    });
</script>
{% endblock %}